import * as React from 'react';
import { Device, ScriptResult } from './types';

interface DeviceContextType {
  devices: Device[];
  loading: boolean;
  refresh: () => Promise<void>;
  executeScript: (deviceId: string, script: string) => Promise<void>;
  scriptResults: Map<string, ScriptResult>;
}

const DeviceContext = React.createContext<DeviceContextType>({
  devices: [],
  loading: false,
  refresh: async () => {},
  executeScript: async () => {},
  scriptResults: new Map(),
});

export const DeviceProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [devices, setDevices] = React.useState<Device[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [scriptResults, setScriptResults] = React.useState<Map<string, ScriptResult>>(new Map());

  const refresh = React.useCallback(async () => {
    if (!window.ipcApi) {
      console.error('ipcApi未定义');
      return;
    }

    setLoading(true);
    try {
      const result = await window.ipcApi.scanDevices();
      console.log('扫描到设备:', result);
      if (result.success) {
        setDevices(result.devices || []);
      } else {
        console.error('扫描设备失败:', result.error);
      }
    } catch (error) {
      console.error('扫描设备失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 监听设备连接
  React.useEffect(() => {
    if (!window.ipcApi) return;

    const removeConnectedListener = window.ipcApi.onDeviceConnected((event) => {
      setDevices(prev => {
        const index = prev.findIndex(d => d.id === event.deviceId);
        if (index === -1) {
          return [...prev, {
            id: event.deviceId,
            model: event.model,
            isWebSocket: event.isWebSocket
          }];
        }
        return prev;
      });
    });

    const removeDisconnectedListener = window.ipcApi.onDeviceDisconnected((event) => {
      setDevices(prev => prev.filter(d => d.id !== event.deviceId));
      setScriptResults(prev => {
        const next = new Map(prev);
        next.delete(event.deviceId);
        return next;
      });
    });

    return () => {
      removeConnectedListener();
      removeDisconnectedListener();
    };
  }, []);

  // 监听脚本执行结果
  React.useEffect(() => {
    if (!window.ipcApi) return;

    const removeScriptResultListener = window.ipcApi.onScriptResult((result) => {
      setScriptResults(prev => {
        const next = new Map(prev);
        next.set(result.deviceId, result);
        return next;
      });
    });

    return () => {
      removeScriptResultListener();
    };
  }, []);

  // 执行脚本
  const executeScript = React.useCallback(async (deviceId: string, script: string) => {
    if (!window.ipcApi) {
      throw new Error('ipcApi未定义');
    }

    try {
      const result = await window.ipcApi.executeScript({
        deviceId,
        scriptContent: script
      });

      if (!result.success) {
        throw new Error(result.error || '执行失败');
      }
    } catch (error) {
      console.error('执行脚本失败:', error);
      throw error;
    }
  }, []);

  React.useEffect(() => {
    refresh();
  }, [refresh]);

  return (
    <DeviceContext.Provider value={{ devices, loading, refresh, executeScript, scriptResults }}>
      {children}
    </DeviceContext.Provider>
  );
};

export const useDeviceContext = () => {
  const context = React.useContext(DeviceContext);
  if (!context) {
    throw new Error('useDeviceContext必须在DeviceProvider内部使用');
  }
  return context;
}; 